package com.ml.admin.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ml
 * @date 2023/3/9 13:47
 * 邮箱验证码工具类
 */
@Component
public class MailUtil {
    @Resource
    JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String fromMail;

    /**
    发送验证码
     */
    public boolean sendMail(String toMail,String content){
        try {
            MimeMessage messageM = mailSender.createMimeMessage();
            MimeMessageHelper message=new MimeMessageHelper(messageM);
            message.setTo(toMail);
            message.setSubject("kiki验证码");
            message.setText(content);
            message.setFrom(fromMail);
            mailSender.send(messageM);
        }catch (Exception ex){
            return Boolean.FALSE;
        }
        return  Boolean.TRUE;
    }

    /**生成随机的六位验证码*/
    public String CreateCode() {
        String dates = "0123456789";
        StringBuilder code = new StringBuilder();
        Random r = new Random();
        for (int i = 0; i < 6; i++) {
            int index = r.nextInt(dates.length());
            char c = dates.charAt(index);
            code.append(c);
        }
        return code.toString();
    }
    /**
     * 判断邮箱格式是否正确
     * @param email 邮箱
     * @return false或者true
     */

    public  boolean isEmail(String email) {

        //\w表示a-z，A-Z，0-9(\\转义符)
        String str = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        if (email == null || email.length() < 1 || email.length() > 256) {
            return false;
        }

        Pattern pattern=Pattern.compile(str);
        Matcher matcher=pattern.matcher(email);
        return matcher.matches();
    }
}
